<?php


namespace app\plugin\controller\merchant;


use app\common\controller\AppCommon;
use app\plugin\controller\merchant\com\MerchantManager;
use app\service\MerchantCredits;
use app\service\MerchantMsg;
use app\service\Page;
use think\Db;
use think\Log;

class Finance extends MerchantManager
{
    //货款记录
    public function index()
    {
        $where = [];
        $orderBy = 'id desc';
        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;
        $type = !empty($this->param['type']) ? intval($this->param['type']) : '';
        $keyword = !empty($this->param['keyword']) ? trim($this->param['keyword']) : '';

        $where['uid'] = $this->m_uid;
        if (!empty($keyword)) {
            $where['remark'] = ['like', '%' . $keyword . '%'];
        }

        if (!empty($type)) {
            $where['type'] = $type;
        }

        $total = AppCommon::data_count('plugin_merchant_credit_log', $where);
        $data = AppCommon::data_list('plugin_merchant_credit_log', $where, $page . ',' . $pageSize, '*', $orderBy);


        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);
        return $this->fetch();
    }

    //todo 缓存
    public function withdraw()
    {
        $credit = AppCommon::data_get_column('plugin_merchant_credits', ['uid' => $this->m_uid], 'credit');
        $data[] = [
            'name' => '可提现货款',
            'num' => $credit ? $credit : '0.00',
            'desc' => '已结算在账户中可提现货款 <span class="btn btn-outline-info btn-sm bs-left-10 to-apply" title="去申请提现" >去提现</span>'
        ];
        //已完成的订单
        $query = AppCommon::query("select  sum(if(is_settlement=1,pay_price-refund_total,0)) as total_se, "
            . " sum(if(is_settlement=0,pay_price-refund_total,0)) as total_nse from " . table_name('order')
            . " where store_num=:store_num and status>=:status and is_parent=:is_parent",
            ['store_num' => $this->store_num, 'status' => 3, 'is_parent' => 0]);
        $query = !empty($query[0]) ? $query[0] : null;

        $data[] = [
            'name' => '在途货款',
            'num' => !empty($query['total_nse']) ? $query['total_nse'] : '0.00',
            'desc' => '有效订单，但是订单未完成状态，未到结算时间'
        ];
        $data[] = [
            'name' => '累计结算货款',
            'num' => !empty($query['total_se']) ? $query['total_se'] : '0.00',
            'desc' => '累计结算的所有订单总货款数量'
        ];

        $this->assign('data', $data);
        return $this->fetch();
    }

    public function withdraw_apply()
    {
        //当前余额
        $creditInfo = MerchantCredits::get($this->m_uid, 'credit');
        $credit = $creditInfo['credit'];
        //手续费
        $fee = number_format(0, 2);
        if (IS_AJAX) {
            $log = AppCommon::data_get('withdraw_log', ['uid' => $this->m_uid, 'uid_type' => 2, 'status' => 0], 'id', 'id desc');
            if (!empty($log['id'])) {
                data_return('当前有待审核申请，请耐心等待后台审核', -1);
            }
            $num = floatval($this->param['num']);
            if (empty($num) || $num > $credit) {
                data_return('请填写提现金额且不得超过当前余额：' . $credit, -1);
            }
            if (empty($this->param['username'])) {
                data_return('请填写真实姓名', -1);
            }
            if (empty($this->param['to_account'])) {
                data_return('请填写提现到账账户', -1);
            }
            if (empty($this->param['to_type']) || !in_array($this->param['to_type'], [1, 2, 3])) {
                data_return('暂不支持的提现方式', -1);
            }
            $order_no = 'bs' . date('YmdHis') . get_random(4, 1);
            while (true) {
                $has = AppCommon::data_get('withdraw_log', ['order_no' => $order_no], 'id');
                if (empty($has['id'])) {
                    break;
                }
                $order_no = 'bs' . date('YmdHis') . get_random(4, 1);
            }

            Db::startTrans();
            $afterNum = $credit - $num;
            $arr = [
                'order_no' => $order_no,
                'add_time' => time(),
                'up_time' => time(),
                'num' => $num,
                'fee' => $fee,
                'username' => strip_tags($this->param['username']),
                'to_account' => strip_tags($this->param['to_account']),
                'to_type' => intval($this->param['to_type']),
                'uid' => $this->m_uid,
                'uid_type' => 2
            ];
            $res = AppCommon::data_add('withdraw_log', $arr);
            if (!$res) {
                Db::rollback();
                data_return('申请提现失败，请稍后重试', -1);
            }
            //申请金额+手续费
            $needNum = abs(abs($num) + abs($fee));
            $upCredit = MerchantCredits::update($this->m_uid, 'credit', -$needNum, ['remark' => '申请提现', 'type' => 2]);

            if (!$upCredit) {
                Db::rollback();
                data_return('申请提现扣除余额失败，请稍后重试', -1);
            }
            Db::commit();
            MerchantMsg::add($this->m_uid, [
                'title' => '你的提现申请已成功提交',
                'content' => '后台已记录您的申请，1~7个工作日完成审核，请您耐心等待，如有疑问请联系客服。',
                'type' => 1
            ]);
            data_return('已提交申请，请耐心等待审核');
        }
        //上一次申请记录
        $data = AppCommon::data_get('withdraw_log', ['uid' => $this->m_uid, 'uid_type' => 2], 'username,to_account,to_type', 'id desc');

        $data['credit'] = $credit ? $credit : number_format(0, 2);
        //手续费
        $data['fee'] = $fee;
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function withdraw_log()
    {
        $where = [
            'uid' => $this->m_uid
        ];
        $orderBy = 'id desc';
        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;
        $total = AppCommon::data_count('withdraw_log', $where);
        $data = AppCommon::data_list('withdraw_log', $where, $page . ',' . $pageSize, '*', $orderBy);
        if ($total) {
            foreach ($data as &$value) {
                $value['status_desc'] = '<span class="bs-blue">待审核</span>';
                if ($value['status'] == 1) {
                    $value['status_desc'] = '<span class="bs-green">已通过</span>';
                } elseif ($value['status'] == -1) {
                    $value['status_desc'] = '<span class="bs-red">已驳回</span>';
                }
                if ($value['to_type'] == 1) {
                    $value['to_type_desc'] = '<span class="bs-green">支付宝</span>';
                } elseif ($value['to_type'] == 2) {
                    $value['to_type_desc'] = '<span class="bs-red">微信</span>';
                } else {
                    $value['to_type_desc'] = '<span class="bs-grey">银行卡</span>';
                }
                $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
                $value['up_time'] = date('Y-m-d H:i:s', $value['up_time']);
            }
            unset($value);
        }

        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);
        return $this->fetch();
    }
}